package com.it.rabbitmqwithjiang.Controller;

import com.it.rabbitmqwithjiang.Dao.MessageDao;
import com.it.rabbitmqwithjiang.Dao.TopicMessage;
import com.it.rabbitmqwithjiang.Service.Impl.PublisherImpl;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;

@RestController
public class RabbitMQController {

    @RequestMapping("demo")
    public String demo(){
        return "demo";
    }

    @Autowired
    PublisherImpl publisher;

    @RequestMapping(value="/defaultdirect",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void produce(@RequestParam("messageDao") MessageDao messageDao) throws Exception{    //默认为轮询
        publisher.senddefaultdirectMessage("defaultDirect", messageDao);
    }

    @RequestMapping(value="/direct",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void direct(@RequestParam("messageDao") MessageDao messageDao, @RequestParam("routingkey") TopicMessage top){
        publisher.senddirectMessage(messageDao, top.getRoutingkey());   //black 1 号    white 和blue 2 号
    }

    @RequestMapping(value="/fanout",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void fanout(@RequestParam("messageDao") MessageDao messageDao) throws Exception{    //两个都可以收到
        publisher.sendfanoutMessage(messageDao);
    }


    @RequestMapping(value="/topic",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public void topic(@RequestParam("messageDao") MessageDao messageDao, @RequestParam("routingkey") TopicMessage top){
        publisher.sendtopicMessage(messageDao, top.getRoutingkey());    // *.white.* 1号    *.*.black和blue.# 2 号
    }


    public void TTLMessage() throws InterruptedException {
        // 1.准备消息
        Message message = MessageBuilder
                .withBody("hello, ttl messsage".getBytes(StandardCharsets.UTF_8))
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                //我们也可以在发送消息的时候设置消息过期时间,设置超时时间为5s
            //    .setExpiration("5000")
                .build();
        // 2.发送消息
        publisher.TTLMessage(message);


    }



}
